import json
import logging
from logging import handlers

# 日志初始化
from apiAutomation import app


def log_init():
    # 创建日志器对象
    logger = logging.getLogger()

    # 设置日志器级别
    logger.setLevel(logging.INFO)

    # 创建处理器对象
    # 控制台处理器
    sh = logging.StreamHandler()
    # 文本处理器
    log_file = app.BATH_PATH + "/log/P2P.log"
    fh = logging.handlers.TimedRotatingFileHandler(log_file,
                                                   when="midnight",
                                                   interval=1,
                                                   backupCount=7,
                                                   encoding="UTF-8")

    # 创建格式化器对象
    fmt = "%(asctime)s %(levelname)s [%(name)s] [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
    formatter = logging.Formatter(fmt)

    # 将格式化器对象添加到处理器对象
    sh.setFormatter(formatter)
    fh.setFormatter(formatter)

    # 将处理器对象添加到日志器对象
    logger.addHandler(sh)
    logger.addHandler(fh)


# 公共断言
def common_assert(self, response, status_code, status, msg):
    res_json = response.json()
    self.assertEqual(status_code, response.status_code)
    self.assertEqual(status, res_json["code"])
    self.assertEqual(msg, res_json["msg"])


# 读取参数化文件
def read_file(file, api_data, keys):
    data_path = app.BATH_PATH + "/data/" + file + ".json"

    # 将keys分割成一个列表
    keys_list = keys.split(",")

    # 读取文件
    with open(data_path, encoding="utf-8") as f:
        # 读取json文件
        json_data = json.load(f)
        # 获取指定接口的参数化数据
        data = json_data[api_data]
        data_list = []
        # 遍历得到每一条参数化数据
        for i in data.values():
            data_list.append(i)
        # 遍历添加了数据的列表
        test_data = []
        for j in data_list:
            values_list = []
            for k in keys_list:
                key = j.get(k)
                values_list.append(key)
            test_data.append(values_list)
        print("test_data:", test_data)
    return test_data

# 连接数据库


    # 创建数据库连接对象

    # 创建游标对象

    # 输入要执行的sql

    # 通过游标对象执行sql（判断是修改sql还是查询）

    # 输出执行结果

    # 关闭游标对象

    # 关闭数据库连接对象

if __name__ == '__main__':
    read_file("login", "login", "username")
